package com.ruoyi.web.controller.face.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Face;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.modules.service.FaceService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.face.domain.Sample;
import com.ruoyi.web.controller.face.face.AipFace;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;

/**
 * 人脸注册
 */
@RestController
@RequestMapping("/baidu/face")
public class FaceController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private FaceService faceService;

    public static JSONObject res = null;

    public static void setRes(JSONObject res) {
        FaceController.res = res;
    }

    /**
     * 注册人脸
     * @param userId 用户编号
     * @param image 人脸图片
     * @return
     */
    @ApiOperation("注册人脸")
    @Log(title = "注册人脸", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult addInfo(@RequestParam("userId") Long userId, @RequestParam("image") String image)
    {
        // 初始化一个AipFace
        AipFace client = new AipFace(Sample.APP_ID, Sample.API_KEY, Sample.SECRET_KEY);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        System.out.println("拍照的人脸图片BASE64为(已去掉前缀): " + image);
        JSONObject addInfo = new Sample().addInfo(client, image);
        System.out.println("注册的人脸特征: " + addInfo);

        SysUser sysUser = userService.selectUserById(userId);

        AjaxResult ajax = AjaxResult.success();

        try {
            JSONObject result = addInfo.getJSONObject("result");
            res = result;
        } catch (Exception e) {
            AjaxResult.error("人脸注册失败,请重试!");
        }

        if (res != null) {
            // {"face_token":"ae7f619b832acb7276fe344853c3021c","location":{"top":73.36,"left":64.6,"rotation":-3,"width":98,"height":66}}
            System.out.println("result:" + res);

            String face_token = res.getString("face_token");
            JSONObject location = res.getJSONObject("location"); // 人脸在图片中的位置
            double top = location.getDouble("top"); // 人脸区域离上边界的距离
            double left = location.getDouble("left"); // 人脸区域离左边界的距离
            double rotation = location.getDouble("rotation"); // 人脸框相对于竖直方向的顺时针旋转角
            Integer width = location.getInt("width"); // 人脸区域的宽度
            Integer height = location.getInt("height"); // 人脸区域的高度

            // 保存更新
            Face face = new Face();
            face.setCreateTime(new Date());
            face.setFaceToken(face_token);
            face.setTop(top);
            face.setLefts(left);
            face.setRotation(rotation);
            face.setWidth(width);
            face.setHeight(height);
            face.setFeature(image);
            face.setUserId(userId);
            face.setUserGroupId(String.valueOf(userId));

            System.out.println("face: " + face);

           if (faceService.insertFace(face) > 0) {
               ajax.put("msg", "人脸注册成功!");

               Face newFace = faceService.selectFaceByUserIdAndNewCreateTime(userId);

               System.out.println("根据userId和最新时间查询到的最新Face记录: " + newFace);

               Long faceId = newFace.getFaceId();

               // 直接去更新用户会使角色菜单无法更新，直接变为空，不可取
               userService.updateFaceId(userId, faceId);

               ajax.put("userData", userService.selectUserById(userId));
           }

        }

           String error_msg = addInfo.getString("error_msg");
           if (error_msg.contains("left_eye")) {
               ajax.put("msg", "左眼被遮挡!");
            } else if (error_msg.contains("right_eye")) {
               ajax.put("msg", "右眼被遮挡!");
            } else if (error_msg.contains("nose")) {
               ajax.put("msg", "鼻子被遮挡!");
            } else if (error_msg.contains("mouth")) {
               ajax.put("msg", "嘴巴被遮挡!");
            } else if (error_msg.contains("left")) {
               ajax.put("msg", "左脸颊被遮挡!");
            } else if (error_msg.contains("right")) {
               ajax.put("msg", "右脸颊被遮挡!");
            } else if (error_msg.contains("chin")) {
               ajax.put("msg", "下巴被遮挡!");
            } else if (error_msg.contains("face")) {
               ajax.put("msg", "光线不足!");
            } else if (error_msg.contains("SUCCESS")) {
               ajax.put("msg", "人脸注册成功!");
           } else {
               ajax.put("msg", "未识别到人脸,请对准重试!");
           }
        return ajax;
    }

    /**
     * 查询数据库存储的人脸库
     * @param face 人脸对象
     * @return
     */
    @GetMapping("/all")
    public TableDataInfo getAllFace(Face face) {
        startPage();
        List<Face> faceList = faceService.selectFaceList(face);
        return getDataTable(faceList);
    }
}
